package com.you.atlas.web.home.module.screen;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.citrus.service.uribroker.uri.URIBroker;
import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.Navigator;
import com.alibaba.citrus.turbine.TurbineRunData;
import com.alibaba.common.logging.Logger;
import com.alibaba.common.logging.LoggerFactory;
import com.google.gdata.client.douban.DoubanService;
import com.google.gdata.data.douban.UserEntry;
import com.you.atlas.web.home.helper.DoubanClientHelper;
import com.you.common.webx.AuthContext;
import com.you.member.dal.dao.AccountBindDAO;
import com.you.member.dal.dao.dataobject.AccountBindDO;

public class DoubanBind {

    private Logger         LOGGER = LoggerFactory.getLogger(DoubanBind.class);

    @Autowired
    private AccountBindDAO accountBindDAO;

    public void execute(HttpServletRequest request, TurbineRunData rundata, Context context, Navigator navigator) {
        String requestToken = rundata.getRequest().getParameter("oauth_token");
        Object secret = rundata.getRequest().getSession().getAttribute("douban_secret");

        if (requestToken == null || secret == null) {
            DoubanService myService = DoubanClientHelper.getDoubanService();
            URIBroker uriBroker = navigator.redirectTo("homeModule").withTarget("doubanBind").uri();
            String url = myService.getAuthorizationUrl(uriBroker.render());
            String osecret = myService.getRequestTokenSecret();
            rundata.getRequest().getSession().setAttribute("douban_secret", osecret);
            navigator.redirectToLocation(url);
            return;
        }
        try {
        	DoubanService myService = DoubanClientHelper.getDoubanService();
        	myService.setRequestToken(requestToken);
        	myService.setRequestTokenSecret(secret.toString());
        	String accessToken = DoubanClientHelper.accessTokenToString(myService.getAccessToken());
        	request.setAttribute("accessToken", accessToken);
            UserEntry user = myService.getAuthorizedUser();
            Long memberId = AuthContext.getContext().getMemberId();
            if (memberId == null) {
                navigator.redirectTo("homeModule").withTarget("nocookie.vm");
                return;
            }
            createAccountBind(user.getId(), memberId, accessToken);
            navigator.redirectTo("memberModule").withTarget("bind.vm");
        } catch (Exception e) {
            LOGGER.error("douban bind error, douban_secret=" + secret.toString(), e);
            navigator.redirectTo("homeModule").withTarget("nocookie.vm");
        }
    }

    private void createAccountBind(String doubanId, Long memberId, String accessToken) {
        AccountBindDO accountBind = accountBindDAO.find(doubanId, "douban");
        if (accountBind != null) {
            accountBind.setDoubanId(null);
            accountBind.setDoubanToken(null);
            accountBind.setDoubanSync(null);
            accountBindDAO.update(accountBind);
        }
        AccountBindDO accountBindFromDB = accountBindDAO.findByMemberId(memberId);
        if (accountBindFromDB == null) {
            AccountBindDO accountBindDO = new AccountBindDO();
            accountBindDO.setDoubanId(doubanId);
            accountBindDO.setMemberId(memberId);
            accountBindDO.setDoubanToken(accessToken);
            accountBindDO.setDoubanSync("OPEN");
            accountBindDAO.create(accountBindDO);
        } else {
            accountBindFromDB.setDoubanId(doubanId);
            accountBindFromDB.setDoubanToken(accessToken);
            accountBindFromDB.setDoubanSync("OPEN");
            accountBindDAO.update(accountBindFromDB);
        }

    }
}
